package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements CourseCategoryService {
    @Autowired
    CourseCategoryMapper courseCategoryMapper;

    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);

        //将查询结果的List 转化为 Map 集合 | filter(item -> !id.equals(item.getId())) 过滤掉集合内 id字段为传入参数 id的元素
        Map<String, CourseCategoryTreeDto> map = courseCategoryTreeDtos
                .stream()
                .filter(item -> !id.equals(item.getId()))
                .collect(Collectors.toMap(key -> key.getId(), value -> value, (key1, key2) -> key2));

        List<CourseCategoryTreeDto> categoryTreeDtos = new ArrayList<>();

        courseCategoryTreeDtos
                .stream()
                .filter(item -> !id.equals(item.getId()))
                .forEach(item -> {
                    //判断item父节点id是否和传入参数id相同 相同则加入到集合
                    if (item.getParentid().equals(id)){
                        categoryTreeDtos.add(item);
                    }
                    //从Map集合内找到当前节点的父节点
                    CourseCategoryTreeDto courseCategoryTreeDto = map.get(item.getParentid());

                    //判断父节点是否为空,不为空则将该遍历的节点放入父节点ChildrenTreeNodes存入
                    if(courseCategoryTreeDto !=null){
                        //存入ChildrenTreeNodes属性前先判断该属性是否为空,为空则New一个新的
                        if(courseCategoryTreeDto.getChildrenTreeNodes() == null){
                            courseCategoryTreeDto.setChildrenTreeNodes(new ArrayList<CourseCategory>());
                        }

                        //往父节点的ChildrenTreeNodes存入子节点
                        courseCategoryTreeDto.getChildrenTreeNodes().add(item);
                    }
                });
        return categoryTreeDtos;
    }
}
